<template>
	<view class="container">
		<!-- 顶部信息卡片 (复用 Exchangerecords 样式) -->
		<view class="record-item top-info-card">
			<!-- 主信息区 -->
			<view class="item-main">
				<image class="goods-image" :src="details.goodsImg || '/static/img/default_goods.png'" mode="aspectFill"></image>
				<view class="item-info-wrapper">
					<view class="goods-title-line">
						<text class="goods-name">{{details.goodsName}}</text>
						<text class="goods-code">x{{details.quantity}}</text>
					</view>
					<view class="item-info">
						<text class="info-label">兑换用户: </text>
						<text class="info-content">{{details.userName}}({{details.userPhone}})</text>
					</view>
					<view class="item-info">
						<text class="info-label">申请时间: </text>
						<text class="info-content">{{details.createDate}}</text>
					</view>
                    <!-- 兑换方式 -->
                    <view class="item-info">
						<text class="info-label">兑换方式: </text>
						<text class="info-content">{{details.methodExchange === '0' ? '当面兑换' : '快递邮寄兑换'}}</text>
					</view>
				</view>
			</view>
			<!-- 积分信息 -->
			<view class="item-points">
				<image class="points-icon" src="/static/img/icon_points.png" mode="aspectFit"></image>
				<text class="points-value">{{details.price*details.quantity}}积分</text>
			</view>
		</view>

		<!-- 邮寄地址 -->
		<view class="section address-section" v-if="details.methodExchange === '1'">
			<view class="section-header">
                <text class="section-title">邮寄地址：</text>
                <button class="copy-button" size="mini" @click="copyAddress">复制</button>
            </view>
            <view class="address-content">
                <view class="address-line">
                    <text class="recipient-name">{{details.userName}}</text>
                    <text class="recipient-phone">{{details.userPhone}}</text>
                </view>
                <view class="address-detail">{{details.mailingAddress}}</view>
            </view>
		</view>
<!-- SN号 -->
		<view class="section sn-section">
			<text class="section-title">订单：</text>
			<!-- 选择订单 -->
			<view class="order-selection" @click="selectOrder">
			    <view class="order-info" v-if="selectedOrder.batchNo">
			        <text class="order-title">{{selectedOrder.title || ''}}</text>
			        <text class="order-number">订单号：{{selectedOrder.sysOrderNo}}</text>
			    </view>
			    <view class="order-placeholder" v-else>
			        <text>请选择订单</text>
			    </view>
			    <view class="order-arrow">
			        <text class="arrow-icon">></text>
			    </view>
			</view>
		</view>
		<!-- SN号 -->
		<view class="section sn-section">
			<text class="section-title">SN号：</text>
            

            <view class="sn-list">
                <view class="sn-item" v-for="(sn, index) in snList" :key="index">
                    <text class="sn-number">{{sn.sn}}</text>
                    <button class="delete-button" size="mini" @click="deleteSN(index)" v-if="!sn.isFromApi">删除</button>
                </view>
            </view>
            <button class="add-sn-button" 
                :class="{'has-selected': hasSelectedCustomSNs}"
                @click="addSN" 
                :disabled="!selectedOrder.batchNo || hasSelectedCustomSNs">
                {{
                    !selectedOrder.batchNo ? '请先选择订单' : 
                    hasSelectedCustomSNs ? '已选择完机具' : '新增'
                }}
            </button>
		</view>
        
        <!-- 页面底部留白，防止被 footer 遮挡 -->
        <view style="height: 120rpx;"></view> 

		<!-- 固定底部操作栏 -->
		<view class="footer-bar">
            <view class="quantity-info">
                <text>可选{{details.availableQuantity || 0}}台，</text>
                <text>已选{{snList.length}}台</text>
            </view>
			<button class="outbound-button" @click="handleOutbound">出库</button>
		</view>
	</view>
</template>

<script>
const api = require('../../../config/api');
const util = require('../../../utils/util');

export default {
	data() {
		return {
            recordId: null,
			details: { // 存储记录详情
                // 示例结构，需要根据 API 返回调整
                goodsImg: '',
                goodsName: '',
                goodsCode: '',
                allyName: '',
                allyPhone: '',
                applyTime: '',
                exchangeMethod: '', // '0' 当面, '1' 快递
                points: '',
                recipientName: '',
                recipientPhone: '',
                fullAddress: '',
                availableQuantity: 0,
            },
			snList: [ // 存储SN号列表，添加 isFromApi 标识
                // 示例数据
                // { sn: '00003202N7626650006301', isFromApi: true },
                // { sn: '00003202N7626650006305', isFromApi: true },
                // { sn: '00003202N7626650006303', isFromApi: false },
            ],
            loading: true,
            selectedOrder: {
                batchNo: '',
                title: '',
            },
		};
	},
    computed: {
        // 检查是否已经有手动选择的SN（非API返回）
        hasSelectedCustomSNs() {
            return this.snList.some(item => !item.isFromApi);
        }
    },
	onLoad(options) {
        if (options.id) {
            this.recordId = options.id;
            console.log('recordId:', this.recordId);
            // 直接请求详情API，不依赖URL参数中传递的数据
            this.fetchExchangeDetails();
        } else {
            uni.showToast({ title: '无效的记录ID', icon: 'none' });
            uni.navigateBack();
        }
	},
    onShow() {
        // 监听选择SN页面返回的事件
        uni.$off('snSelected'); // 先移除旧监听器
        uni.$on('snSelected', (data) => {
            console.log('接收到选中的SNs:', data.selectedSNs);
            if (data.selectedSNs && Array.isArray(data.selectedSNs)) {
                // 合并并去重 SN 列表
                const currentSNsMap = new Map();
                // 先保留现有的 SN 列表
                this.snList.forEach(item => {
                    currentSNsMap.set(item.sn, item);
                });
                
                // 添加新选择的 SN，标记为非 API 返回
                data.selectedSNs.forEach(sn => {
                    if (!currentSNsMap.has(sn)) {
                        currentSNsMap.set(sn, { sn, isFromApi: false });
                    }
                });
                
                // 转换回数组
                this.snList = Array.from(currentSNsMap.values());
            }
        });
        
        // 监听选择订单页面返回的事件
        uni.$off('selectOrderDate');
        uni.$on('selectOrderDate', (data) => {
            console.log('接收到选中的订单:', data.item);
            if (data.item) {
                this.selectedOrder = data.item;
                // 清空已选择的SN列表
                this.snList = this.snList.filter(item => item.isFromApi);
            }
        });
    },
	methods: {
        // 获取兑换详情
        async fetchExchangeDetails() {
            this.loading = true;
            try {
                // 使用统一的API调用方式获取详情
                const res = await util.request(
                    api.getExchangeDetailUrl + '/' + this.recordId,
                    {},
                    'POST'
                );
                
                console.log('兑换详情:', res);
                
                if (res.code !== 0) {
                    uni.showToast({ title: res.msg || '加载详情失败', icon: 'none' });
                    return;
                }
                
                // 更新数据
                this.details = res.data;
                // 处理SN列表
                if (res.data.snNos) {
                    // 优先处理snNos字段（逗号分隔的字符串）
                    if (typeof res.data.snNos === 'string') {
                        const snArray = res.data.snNos.split(',').filter(sn => sn.trim() !== '');
                        this.snList = snArray.map(sn => ({ sn, isFromApi: true }));
                    } 
                    // 如果已经是数组则直接使用
                    else if (Array.isArray(res.data.snNos)) {
                        this.snList = res.data.snNos.map(sn => ({ sn, isFromApi: true }));
                    }
                } else {
                    this.snList = []; // 清空SN列表
                }
                
            } catch (error) {
                console.error("加载详情失败:", error);
                uni.showToast({ title: '网络错误', icon: 'none' });
            } finally {
                this.loading = false;
            }
        },

        // 复制地址
		copyAddress() {
            const addressText = `${this.details.userName} ${this.details.userPhone}\n${this.details.mailingAddress}`;
            uni.setClipboardData({
                data: addressText,
                success: () => {
                    uni.showToast({ title: '地址已复制', icon: 'success' });
                },
                fail: () => {
                     uni.showToast({ title: '复制失败', icon: 'none' });
                }
            });
		},

        // 删除SN
		deleteSN(index) {
            // 可以加个确认框
            uni.showModal({
                title: '确认删除',
                content: `确定要删除SN号 ${this.snList[index].sn} 吗？`,
                success: (res) => {
                    if (res.confirm) {
                         this.snList.splice(index, 1);
                    }
                }
            });
		},

        // 新增SN (跳转到新页面)
		addSN() {
            // 检查是否已选择订单
            if (!this.selectedOrder.batchNo) {
                uni.showToast({ title: '请先选择订单', icon: 'none' });
                return;
            }
            
            // 检查是否已经选择过机具（存在非API返回的SN）
            if (this.hasSelectedCustomSNs) {
                uni.showToast({ title: '已经选择完机具', icon: 'none' });
                return;
            }
            
			// 跳转到选择SN页面，可以传递当前已选SN，方便那边做反选或禁用
            uni.navigateTo({
                 url: `/pages/indexChild/Exchangerecords/SelectSN?recordId=${this.recordId}&selected=${JSON.stringify(this.snList.map(item => item.sn))}&batchNo=${this.selectedOrder.batchNo}` 
            });
		},
        
        // 选择订单方法
        selectOrder() {
            uni.navigateTo({
                url: '/pages/myEquipment/SelectOrder',
                events: {
                    selectOrder: (data) => {
                        // 这里不需要处理，在onShow里通过全局事件监听处理
                    },
                },
                success: (res) => {
                    res.eventChannel.emit('SelectOrder', {
                        data: '选择订单'
                    });
                }
            });
        },
        
        // 处理出库
        async handleOutbound() {
            // 检查是否已选择订单
            if (!this.selectedOrder.batchNo) {
                uni.showToast({ title: '请选择订单', icon: 'none' });
                return;
            }
            
            if (this.snList.length === 0) {
                uni.showToast({ title: '请添加SN号', icon: 'none' });
                return;
            }
            
            // 检查是否有新增的SN号
            const hasNewSN = this.snList.some(item => !item.isFromApi);
            if (!hasNewSN) {
                uni.showToast({ title: '请选择机器', icon: 'none' });
                return;
            }
            
            // 直接提交出库
            this.submitOutbound();
        },
        
        // 提交出库请求
        async submitOutbound() {
            try {
                uni.showLoading({ title: '提交中...' });
                
                // 准备提交数据
                const outboundData = {
                    id: this.recordId,
                    batchNo: this.selectedOrder.batchNo, // 添加订单批次号
                    snList: this.snList
                        .filter(item => !item.isFromApi) // 只获取从 SelectSN 页面选择的 SN
                        .map(item => item.sn) // 提取 sn 值
                };
                
                // 调用出库API
                const res = await util.request(
                    api.outboundExchangeUrl,
                    outboundData,
                    'POST'
                );
                
                console.log('出库结果:', res);
                
                if (res.code !== 0) {
                    uni.showToast({ title: res.msg || '出库失败', icon: 'none' });
                    return;
                }
                
                uni.showToast({ title: '出库成功', icon: 'success' });
                
                // 返回兑换记录列表页面
                setTimeout(() => {
                    uni.navigateBack();
                }, 1500);
                
            } catch (error) {
                console.error('出库失败:', error);
                uni.showToast({ title: '网络错误', icon: 'none' });
            } finally {
                uni.hideLoading();
            }
        },
	}
};
</script>

<style lang="scss" scoped>
.container {
	background-color: #f5f5f5;
	min-height: 100vh;
    padding-bottom: 140rpx; /* 底部留出足够空间给 footer bar */
}

/* --- 复用 Exchangerecords.vue 的样式 --- */
.record-item {
    background-color: #fff;
    border-radius: 10rpx;
    padding: 30rpx;
    margin-bottom: 20rpx;
    box-shadow: 0 2rpx 6rpx rgba(0,0,0,0.05);
    
    &.top-info-card {
        margin: 20rpx; // 给顶部卡片一些外边距
    }
    
    .item-main {
        display: flex;
        align-items: center; 
    }
    
    .goods-image {
        width: 120rpx;
        height: 120rpx;
        border-radius: 8rpx;
        margin-right: 20rpx;
        background-color: #f0f0f0; 
        flex-shrink: 0; 
    }
    
    .item-info-wrapper {
        flex: 1; 
        min-width: 0; 
        
        .goods-title-line {
            display: flex;
            justify-content: space-between; 
            align-items: center;
            margin-bottom: 10rpx;
            
            .goods-name {
                font-size: 30rpx;
                font-weight: 500;
                color: #333;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
                margin-right: 10rpx; 
            }
            
            .goods-code {
                font-size: 28rpx;
                color: #999;
                white-space: nowrap; 
                flex-shrink: 0; 
            }
        }
        
        .item-info {
            font-size: 26rpx; 
            color: #666;
            margin-bottom: 6rpx; 
            display: flex;
            align-items: center;
            overflow: hidden;
            
            .info-label {
                color: #999;
                margin-right: 5rpx; 
                white-space: nowrap; 
            }
            
            .info-content {
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
            }
            
            &:last-child {
                margin-bottom: 0;
            }
        }
    }
    
    .item-points {
        display: flex;
        justify-content: flex-end; 
        align-items: center;
        margin-top: 15rpx; 
        
        .points-icon {
            width: 36rpx; 
            height: 36rpx;
            margin-right: 8rpx;
        }
        
        .points-value {
            font-size: 30rpx; 
            color: #FF5B5B;
            font-weight: 500;
            white-space: nowrap; 
        }
    }
}
/* --- 复用样式结束 --- */

.section {
    background-color: #fff;
    margin: 0 20rpx 20rpx 20rpx;
    padding: 30rpx;
    border-radius: 10rpx;
    box-shadow: 0 2rpx 6rpx rgba(0,0,0,0.05);
}

.section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;
}

.section-title {
    font-size: 30rpx;
    font-weight: 500;
    color: #333;
}

.copy-button {
    border: 1rpx solid #6A9FFB;
    color: #6A9FFB;
    background-color: #fff;
    padding: 5rpx 20rpx;
    line-height: 1.5;
    font-size: 24rpx;
    border-radius: 6rpx;
    // 移除按钮默认边距
    margin: 0;
     &::after {
        border: none;
    }
}

.address-section {
    .address-content {
        font-size: 28rpx;
        color: #333;
        line-height: 1.6;
        .address-line {
            margin-bottom: 5rpx;
            .recipient-phone {
                margin-left: 20rpx;
            }
        }
    }
}

.sn-section {
    .order-selection {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 20rpx 0;
        margin-top: 20rpx;
        margin-bottom: 20rpx;
        border-bottom: 1rpx solid #f5f5f5;
        
        .order-info {
            display: flex;
            flex-direction: column;
            font-size: 28rpx;
            color: #333;
            
            .order-title {
                font-weight: 500;
                margin-bottom: 5rpx;
            }
            
            .order-number {
                font-size: 24rpx;
                color: #666;
            }
        }
        
        .order-placeholder {
            font-size: 28rpx;
            color: #999;
        }
        
        .order-arrow {
            font-size: 28rpx;
            color: #999;
            
            .arrow-icon {
                font-size: 32rpx;
            }
        }
    }
    .sn-list {
        margin-top: 10rpx;
    }
    .sn-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 20rpx 0;
        border-bottom: 1rpx solid #f5f5f5;
        
        .sn-number {
            font-size: 28rpx;
            color: #333;
        }
        
        .delete-button {
            border: 1rpx solid #FF5B5B;
            color: #FF5B5B;
            background-color: #fff;
            padding: 5rpx 20rpx;
            line-height: 1.5;
            font-size: 24rpx;
            border-radius: 6rpx;
            margin: 0;
             &::after {
                border: none;
            }
        }
        
        &:last-child {
            border-bottom: none;
        }
    }
    .add-sn-button {
        margin-top: 30rpx;
        background-color: #f5f5f5;
        color: #666;
        font-size: 28rpx;
        height: 70rpx;
        line-height: 70rpx;
         &::after {
            border: none;
        }
        
        &[disabled] {
            color: #999;
            background-color: #eee;
        }
        
        // 专门针对已选择完机具状态的样式
        &.has-selected {
            background-color: #f0f0f0;
            color: #999;
        }
    }
}

.footer-bar {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    width: 100%;
    // height: 120rpx; // 高度可以自适应或根据需要调整
    background-color: #fff;
    border-top: 1rpx solid #eee;
    display: flex;
    flex-direction: column; /* 改为列布局 */
    align-items: flex-start; /* 左对齐 */
    // justify-content: space-between; // 移除
    padding: 20rpx 30rpx; /* 调整内边距 */
    box-sizing: border-box;

    .quantity-info {
        font-size: 28rpx;
        color: #6A9FFB;
        margin-bottom: 15rpx; /* 增加与按钮的间距 */
    }

    .outbound-button {
        background-color: #6A9FFB;
        color: #fff;
        border: none;
        border-radius: 40rpx;
        height: 80rpx;
        line-height: 80rpx;
        // padding: 0 80rpx; // 移除固定 padding
        font-size: 30rpx;
        width: 90%; /* 设置按钮宽度 */
        align-self: center; /* 在列布局中水平居中 */
         &::after {
            border: none;
        }
    }
}

</style> 